package com.zhangtai.modules.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.LeaveConst;
import com.zhangtai.modules.controller.admin.CommonController;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.ImgUrlDao;
import com.zhangtai.modules.dao.ShiftDao;
import com.zhangtai.modules.dto.DistributeLeaveDto;
import com.zhangtai.modules.dto.FrequencyDto;
import com.zhangtai.modules.dto.LeaveInfoDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.leave.DistributeLeaveEntity;
import com.zhangtai.modules.entity.leave.LeaveInfoEntity;
import com.zhangtai.modules.entity.leave.ShiftEntity;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.leave.DistributeLeaveService;
import com.zhangtai.modules.service.leave.LeaveInfoService;
import com.zhangtai.modules.service.leave.ShiftService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags="请假调休调班自助端")
@RequestMapping("/memberLeave")
@Slf4j
public class LeaveMemberController {

    @Autowired
    private LeaveInfoService leaveInfoService;

    @Autowired
    private MemberLoginController memberLoginController;
    @Autowired
    private JobController jobController;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private CommonController commonController;
    @Autowired
    private DistributeLeaveService distributeLeaveService;
    @Autowired
    private ShiftService shiftService;
    @Autowired
    private ShiftDao shiftDao;
    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private ImgUrlDao imgUrlDao;

    @PostMapping("/getMemberLeaveList")
    @ApiOperation("获取自助端请假调休列表")
    public R<PageResult<LeaveInfoDto>> getLeaveList(HttpServletRequest request, @RequestBody @Valid MemberLeaveVo vo) throws  Exception{
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        Long oid = data.getLong("id"); //只能查询自己的信息
        String startTime = "";
        String endTime = "";
        if(!StringUtils.isEmpty(vo.getDate())){
            startTime = vo.getDate()+"-01 00:00:00";
            endTime = vo.getDate()+"-31 00:00:00";
        }

        PageResult<LeaveInfoDto> list =  leaveInfoService.getLeaveList(oid,startTime,endTime,vo.getDealStatus(),vo.getPageNum(),vo.getPageSize());
        List<LeaveInfoDto> leaveInfo  = list.getList();
        for(LeaveInfoDto info:leaveInfo){
            info.setUnitname(jobController.orgMap.get(info.getUnitId()));
            info.setJobname(jobController.jobMap.get(info.getJobId()));
        }
        return R.ok(list);
    }

    @PostMapping("/saveOrUpdateLeave")
    @ApiOperation("保存请假调休")
    @Transactional
    public R saveOrUpdateLeave(@RequestBody @Valid LeaveBpmVo vo ,HttpServletRequest request)throws Exception{
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        Long oid = data.getLong("id"); //只能查询自己的信息
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("请先登录");
        }
        //申请时间段跟状态为“审批中”、“审批通过”的休假申请单有交叉时，不允许提交
        List<LeaveInfoEntity> sameTimeList = leaveInfoService.getSameTimeResult(DateUtils.format(vo.getLeaveBeginTime())+" 00:00:00",DateUtils.format(vo.getLeaveEndTime())+" 23:59:59",oid);
        if(!CollectionUtils.isEmpty(sameTimeList)){
            return R.error("申请时间段跟状态为“审批中”、“审批通过”的休假申请单有交叉时，不允许提交");
        }
        Long orgId = employeeInfoEntity.getOrgId();
        Long jobId = employeeInfoEntity.getJobId();
        Long unitId = employeeInfoEntity.getUnitId();
        LeaveInfoEntity leaveInfo = BeanUtilsMabach.doToDto(vo,LeaveInfoEntity.class);
        leaveInfo.setCreateTime(new Date());
        leaveInfo.setOid(oid);
        leaveInfo.setDealStatus(0);
        leaveInfo.setOrgname(jobController.orgMap.get(employeeInfoEntity.getOrgId()));
        leaveInfo.setJobId(jobId);
        leaveInfo.setOrgId(orgId);
        leaveInfo.setUnitId(unitId);
        String[] fileUrls = leaveInfo.getFileUrl().split(",");
        List<String> urls = new ArrayList<>();
        if(fileUrls.length>0){
            for(String fileUrl:fileUrls){
                urls.add(fileUrl);
            }
            commonController.getFileUrls(urls,oid,"请假调休附件");
        }
        if(ObjectUtils.isEmpty(leaveInfo.getId())){
            leaveInfo.setCreateType(vo.getCreateType());
            leaveInfoService.saveE(leaveInfo);
        }else{
            leaveInfoService.updateByIdE(leaveInfo);
        }
        return R.ok();
    }

    @DeleteMapping("/deleteLeave")
    @ApiOperation("删除请假调休")
    @Transactional
    public R deleteLeave(String id){
        if(StringUtils.isEmpty(id)){
            return R.error("请假调休id不存在！");
        }
        leaveInfoService.removeOneById(Long.parseLong(id));
        return R.ok();
    }

    @PostMapping("/getRealLeaveDay")
    @ApiOperation("实际请假时间")
    public R<String> getRealLeaveDay(@RequestBody @Valid RealeLeaveVo vo , HttpServletRequest request)throws Exception{
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        String usercode = data.getString("usercode"); //只能查询自己的信息
        if (ObjectUtils.isEmpty(usercode)){
            return R.error("请先登录");
        }
        // TODO: 2020/12/2  查询ehr实际请假接口返回实际请假天数
        String s = "5";
        return R.ok(s);
    }

    @PostMapping("/getResidueDay")
    @ApiOperation("获取剩余年假")
    public R<String> getResidueDay(HttpServletRequest request)throws Exception{
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        String usercode = data.getString("usercode"); //只能查询自己的信息
        if (ObjectUtils.isEmpty(usercode)){
            return R.error("请先登录");
        }
        // TODO: 2020/12/2  查询ehr获取剩余年假接口
        String s = "5";
        return R.ok(s);
    }

    @PostMapping("/getMemberDistributeLeaveList")
    @ApiOperation("获取零星调休")
    public R<PageResult<DistributeLeaveDto>> getDistributeLeaveList(HttpServletRequest request, DistributeLeaveVo vo)throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){
            return R.error("请先登录");
        }
        Long oid = userInfo.getLong("id");
        PageResult<DistributeLeaveEntity> result = distributeLeaveService.getLeaveList(oid,null,null,null,vo.getPageNum(),vo.getPageSize());
        List<DistributeLeaveEntity> list = result.getList();
        List<DistributeLeaveDto> dtoList = new ArrayList<>();
        for (DistributeLeaveEntity entity:list){
            DistributeLeaveDto dto = BeanUtilsMabach.doToDto(entity,DistributeLeaveDto.class);
            dto.setJobname(jobController.jobMap.get(dto.getJobId()));
            dto.setOrgname(jobController.orgMap.get(dto.getOrgId()));
            dto.setUnitname(jobController.orgMap.get(dto.getUnitId()));
            dtoList.add(dto);
        }
        PageResult<DistributeLeaveDto> dtoResult = new PageResult<>();
        dtoResult.setList(dtoList);
        dtoResult.setCurrPage(result.getCurrPage());
        dtoResult.setPageSize(result.getPageSize());
        dtoResult.setTotalCount(result.getTotalCount());
        dtoResult.setTotalPage(result.getTotalPage());
        return R.ok(dtoResult);
    }

    @PostMapping("/saveOrUpdateDistributeLeave")
    @ApiOperation("保存修改零星调休")
    public R saveOrUpdateDistributeLeave(HttpServletRequest request,@RequestBody @Valid DistributeLeaveEntity entity)throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){
            return R.error("请先登录");
        }
        Long oid = userInfo.getLong("id");
        entity.setOid(oid);
        if(ObjectUtils.isEmpty(entity.getId())){
            EmployeeInfoEntity infoEntity = employeeInfoService.getByIdE(oid);
            entity.setJobId(infoEntity.getJobId());
            entity.setUnitId(infoEntity.getUnitId());
            entity.setOrgId(infoEntity.getOrgId());
            distributeLeaveService.saveE(entity);
        }else{
            DistributeLeaveEntity old = distributeLeaveService.getByIdE(entity.getId());
            if(ObjectUtils.isEmpty(old)){
                return R.error("零星调休不存在，无法修改");
            }else if(!LeaveConst.LEAVE_STATUS_APPLY.equals(old.getStatus())){
                return R.error("该条零星调休未处于待提交状态，无法修改");
            }
            distributeLeaveService.updateByIdE(entity);
        }
        return R.ok();
    }

    @DeleteMapping("/deleteDistributeLeave")
    @ApiOperation("删除零星请假调休")
    @Transactional
    public R deleteDistributeLeave(String id){
        if(StringUtils.isEmpty(id)){
            return R.error("请假调休id不存在！");
        }
        distributeLeaveService.removeOneById(Long.parseLong(id));
        return R.ok();
    }

    @GetMapping("/getShiftPage")
    @ApiOperation(value="分页查询调班列表")
    public R getShiftPage(@RequestParam(value = "shiftDateStart",required = false) String shiftDateStart,
                          @RequestParam(value = "shiftDateEnd",required = false) String shiftDateEnd,
                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          HttpServletRequest request) throws Exception {
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        String oid = data.getString("id"); //只能查询自己的信息
        if (ObjectUtils.isEmpty(oid)){
            return R.error("请先登录");
        }
        PageResult result=  shiftService.queryPage(null,oid,null,null,null,null,shiftDateStart,shiftDateEnd,null,pageNum,pageSize);
        return R.ok(result);
    }

    @GetMapping("/getShiftFrequency")
    @ApiOperation(value="根据调班时间查询调班班次")
    public R getShiftFrequency(@RequestParam(value = "shiftDate") String shiftDate,
                               @RequestParam(value = "shiftOid") String shiftOid,
                               @RequestParam(value = "beShiftOid") String beShiftOid,
                          HttpServletRequest request) throws Exception {
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }
        //暂时自定义
        //后面去东软取
        JSONObject object=new JSONObject();
        FrequencyDto frequencyDto1=new FrequencyDto();
        frequencyDto1.setId("1");
        frequencyDto1.setName("早班");

        FrequencyDto frequencyDto2=new FrequencyDto();
        frequencyDto2.setId("2");
        frequencyDto2.setName("中班");

        FrequencyDto frequencyDto3=new FrequencyDto();
        frequencyDto3.setId("3");
        frequencyDto3.setName("晚班");

        List<FrequencyDto> frequencyList=new ArrayList<>();
        frequencyList.add(frequencyDto1);
        frequencyList.add(frequencyDto2);
        frequencyList.add(frequencyDto3);
        object.put("frequencyList",frequencyList);
        List<FrequencyDto> beFrequencyList=new ArrayList<>();
        beFrequencyList.add(frequencyDto1);
        beFrequencyList.add(frequencyDto2);
        beFrequencyList.add(frequencyDto3);
        object.put("beFrequencyList",beFrequencyList);
       return R.ok(object);
    }

    @GetMapping("/getFrequencyList")
    @ApiOperation(value="查询调班班次列表")
    public R getShiftFrequency() throws Exception {
        //暂时自定义
        //后面去东软取
        List<FrequencyDto> frequencyDtoList=new ArrayList<>();

        FrequencyDto frequencyDto1=new FrequencyDto();
        frequencyDto1.setId("1");
        frequencyDto1.setName("早班");
        frequencyDtoList.add(frequencyDto1);

        FrequencyDto frequencyDto2=new FrequencyDto();
        frequencyDto2.setId("2");
        frequencyDto2.setName("中班");
        frequencyDtoList.add(frequencyDto2);

        FrequencyDto frequencyDto3=new FrequencyDto();
        frequencyDto3.setId("3");
        frequencyDto3.setName("晚班");
        frequencyDtoList.add(frequencyDto3);
        return R.ok(frequencyDtoList);
    }

    @PostMapping("/saveAndUpdateShiftInfo")
    @ApiOperation(value="保存或修改调班信息")
    @SysAuthorityLog(value="保存或修改调班信息")
    @Transactional
    public R saveAndUpdateShiftInfo(@RequestBody @Valid ShiftVo shiftVo, HttpServletRequest request) throws Exception {
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        Long oid = data.getLong("id"); //只能查询自己的信息
        if (ObjectUtils.isEmpty(oid)){
            return R.error("请先登录");
        }
        ShiftEntity shiftEntity = BeanUtilsMabach.doToDto(shiftVo,ShiftEntity.class);
        EmployeeInfoEntity applyEmp=employeeInfoService.getByIdE(oid);
        shiftEntity.setApplyName(applyEmp.getName());
        shiftEntity.setApplyCode(applyEmp.getCode());
        shiftEntity.setApplyOrgId(applyEmp.getOrgId());
        shiftEntity.setApplyUnitId(applyEmp.getUnitId());
        shiftEntity.setApplyJobId(applyEmp.getJobId());
        shiftEntity.setApplyOrgName(jobController.getOrgNameById(applyEmp.getOrgId()));
        shiftEntity.setApplyUnitName(jobController.getOrgNameById(applyEmp.getUnitId()));
        shiftEntity.setApplyJobName(jobController.getJobName(applyEmp.getJobId()));
        EmployeeInfoEntity shiftEmp=employeeInfoService.getByIdE(shiftVo.getShiftOid());
        shiftEntity.setShiftName(shiftEmp.getName());
        shiftEntity.setShiftCode(shiftEmp.getCode());
        shiftEntity.setShiftOrgId(shiftEmp.getOrgId());
        shiftEntity.setShiftUnitId(shiftEmp.getUnitId());
        shiftEntity.setShiftJobId(shiftEmp.getJobId());
        shiftEntity.setShiftOrgName(jobController.getOrgNameById(shiftEmp.getOrgId()));
        shiftEntity.setShiftUnitName(jobController.getOrgNameById(shiftEmp.getUnitId()));
        shiftEntity.setShiftJobName(jobController.getJobName(shiftEmp.getJobId()));
        EmployeeInfoEntity beShiftEmp=employeeInfoService.getByIdE(shiftVo.getBeShiftOid());
        shiftEntity.setBeShiftName(beShiftEmp.getName());
        shiftEntity.setBeShiftCode(beShiftEmp.getCode());
        shiftEntity.setBeShiftOrgId(beShiftEmp.getOrgId());
        shiftEntity.setBeShiftUnitId(beShiftEmp.getUnitId());
        shiftEntity.setBeShiftJobId(beShiftEmp.getJobId());
        shiftEntity.setBeShiftOrgName(jobController.getOrgNameById(beShiftEmp.getOrgId()));
        shiftEntity.setBeShiftUnitName(jobController.getOrgNameById(beShiftEmp.getUnitId()));
        shiftEntity.setBeShiftJobName(jobController.getJobName(beShiftEmp.getJobId()));
        ArrayList<String> fileUrlList=shiftVo.getFileUrlList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(shiftEntity.getShiftOid(), fileUrlList, "调班申请附件",24);
        }
        shiftEntity.setFileUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        shiftEntity.setBeShiftDate(shiftVo.getShiftDate());
        if (shiftVo.getId()==null){
            shiftEntity.setCreateTime(new Date());
            shiftService.saveE(shiftEntity);
        }else{
            shiftService.updateByIdE(shiftEntity);
        }
       return R.ok();
    }


    @DeleteMapping("/deleteShift")
    @ApiOperation("删除调班信息")
    @Transactional
    public R deleteShift(@RequestParam(value = "id",required = true) String id){
        shiftDao.deleteById(Long.parseLong(id));
        return R.ok();
    }



    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList, String name, Integer type){
        for (String s : fileList) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setName(name);
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setType(type);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlEntity.setUrl(s);
            imgUrlService.saveE(imgUrlEntity);
        }

    }
    public String ListToString(ArrayList<String> fileUrlList){
        String Url="";
        for ( String s:fileUrlList){
            Url+=s+",";
        }
        return Url.substring(0,Url.length()-1);
    }


}
